package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.ExceptionContant;
import com.itheima.exception.SQLContainRelationException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());

        List<Clazz> clazzList =  clazzMapper.page(clazzQueryParam);
        for (Clazz clazz : clazzList) {
            if (clazz.getEndDate().isBefore(LocalDate.now())) {
                clazz.setStatus("已结课");
            }else if (clazz.getBeginDate().isAfter(LocalDate.now())){
                clazz.setStatus("未开班");
            }else{
                clazz.setStatus("在读中");
            }
        }
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<>(p.getTotal(),p.getResult());
    }

    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.save(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        Integer i = clazzMapper.countStuNumByClazzId(id);
        if(i > 0){
            throw new SQLContainRelationException(ExceptionContant.CLAZZ);
        }else{
            clazzMapper.deleteById(id);
        }
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.list();
    }
}
